package st.shadow.library.core.base.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;

/**
 * @author zhangyu
 * @date 2019/1/16
 */
public abstract class BaseFragment extends SwipeBackFragment {
    private Unbinder mUnBinder = null;

    /**
     * 设置布局
     *
     * @return 布局
     */
    public abstract Object setLayout();

    /**
     * 进行布局绑定
     */
    public abstract void onBindView(@Nullable Bundle savedInstanceState, View rootView);

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        final View rootView;
        if (setLayout() instanceof Integer) {
            rootView = inflater.inflate((Integer) setLayout(), container, false);
        } else if (setLayout() instanceof View) {
            rootView = (View) setLayout();
        } else {
            throw new ClassCastException("setLayout() type must be int or view");
        }
        mUnBinder = ButterKnife.bind(this, rootView);
        onBindView(savedInstanceState, rootView);
        return rootView;
    }

    private long mLastClickTime = 0;
    private long mLastViewId = -1;

    /**
     * 不封装成静态方法的原因是如果对象被回收，静态方法的变量不会清空，导致判断失败
     *
     * @param view
     * @return
     */
    protected boolean isFastClick(View view) {
        boolean flag = false;
        long currentClickTime = System.currentTimeMillis();
        long viewId = view.getId();
        // 两次点击间隔不能少于200ms
        int MIN_DELAY_TIME = 200;
        if ((Math.abs(currentClickTime - mLastClickTime) < MIN_DELAY_TIME)
                && mLastViewId == viewId) {
            flag = true;
        }
        mLastClickTime = currentClickTime;
        mLastViewId = viewId;
        return flag;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mUnBinder != null) {
            mUnBinder.unbind();
        }
    }
}
